<?php
namespace App\Http\Controllers\Client\Common;

use App\Http\Controllers\ClientController;
use App\Jobs\ExploreApplyJob;
use App\Models\Tools\AliOss;
use App\Models\Tools\Data;
use App\Models\Tools\Period;
use App\Models\Work;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class HistoryExploreController extends ClientController
{
    public function index()
    {
        /**
         * 查询已有的探店记录
         */
        $all = $this->all;
        $pageSize = $all['pageSize'] ?? 10;
        $pageNo = $all['pageNo'] ?? 1;

        // 超时任务
        if(isset($all['overtime'])){
            sleep(1);
            Artisan::call('command:explore_overtime');
        }
        // 自动验收
        if(isset($all['pass'])){
            sleep(1);
            Artisan::call('command:explore_acceptance');
        }
        // 发单超时
        if(isset($all['eo_id'])){
            sleep(1);
            ExploreApplyJob::dispatchNow($all['eo_id']);
        }

        try{
            $where = function($query) use ($all){
                $query->where('eo.we_id','=',$this->we_id);

                // 店铺名
                if(!empty($all['shop_name'])){
                    $query->where('shop.shop_name','like','%'.$all['shop_name'].'%');
                }
                // 店铺id
                if($all['shop_id'] > 0){
                    $query->where('shop.shop_id','=',$all['shop_id']);
                }

                // 接单时间
                if($all['time'] > 0){
                    $time = $all['time'];
                    $time = date('Y-m-d H:i:s', strtotime("-$time days"));
                    $query->whereNotNull('ew.work_id')
                        ->where('ew.receive_time','>',$time);
                }

                if($all['status'] !== -1){
//                    {text: '正在发单', value: 0},
//                    {text: '已接单', value: 1},
//                    {text: '已投稿', value: 2},
//                    {text: '已验收', value: 3},
//                    {text: '待结算', value: 4},
//                    {text: '已结算', value: 5},
//                    {text: '验收不通过', value: 6},
//                    {text: '已取消', value: 7},
                    switch ($all['status']){
                        case 0: // 正在发单：订单正在进行
                            $query->where('eo.status','=',Data::DATA_DB_EXPLORE_ORDER_STATUS_PENDING)
                                ->whereNull('ew.work_id');
                            break;
                        case 1: // 已接单
                            $query->whereNotNull('ew.work_id')
                                ->where('ew.status','=',Data::DATA_DB_EXPLORE_WORK_STATUS_INIT);
                            break;
                        case 2: // 已投稿
                            $query->whereNotNull('ew.work_id')
                                ->where('ew.status','=',Data::DATA_DB_EXPLORE_WORK_STATUS_SUBMIT);
                            break;
                        case 3: // 已验收
                            $query->whereNotNull('ew.work_id')
                                ->where('ew.status','=',Data::DATA_DB_EXPLORE_WORK_STATUS_ACCEPTED);
                            break;
                        case 4: // 待结算
                            $query->whereNotNull('ew.work_id')
                                ->where('ew.status','=',Data::DATA_DB_EXPLORE_WORK_STATUS_CHECK);
                            break;
                        case 5: // 已结算
                            $query->whereNotNull('ew.work_id')
                                ->where('ew.status','=',Data::DATA_DB_EXPLORE_WORK_STATUS_SETTLEMENT);
                            break;
                        case 6: // 验收不通过
                            $query->whereNotNull('ew.work_id')
                                ->where('ew.status','=',Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE);
                            break;
                        case 7: // 已取消:订单取消无人接单或工单取消
                            $query->whereRaw('((eo.status = '.Data::DATA_DB_EXPLORE_ORDER_STATUS_FINISHED .' AND ew.work_id IS NULL) OR ew.status = '.Data::DATA_DB_EXPLORE_WORK_STATUS_ERROR.')');
                            break;
                    }
                }
            };


            // 查询订单记录
            $explore_history = DB::table('explore_order as eo')
                ->leftJoin('shop','eo.shop_id','=','shop.shop_id')
                ->leftJoin('explore_channel as ec','eo.channel_id','=','ec.channel_id')
                ->leftJoin('explore_work as ew','eo.eo_id','=','ew.eo_id')
                ->where($where)
                ->orderByDesc('eo.eo_id')
                ->skip(($pageNo - 1) * $pageSize)
                ->take($pageSize)
                ->select('eo.eo_id','eo.shop_id','eo.channel_id','eo.start_date','eo.end_date','eo.total_num','eo.remaining_num',
                    'eo.distribution_num','eo.pending_num','eo.success_num','eo.failed_num','eo.status','eo.created_at','eo.remark','eo.shop_img',
                    'shop.shop_name','ec.channel_name')
                ->get()
                ->map(function($item){
                    $item->status_name = Data::$exploreOrderStatus[$item->status];
                    $item->shop_img = $item->shop_img === ''? []: explode(',', $item->shop_img);
                    $item->canceled_at = 2 * 24 * 60 * 60 - (time() - strtotime($item->created_at)); // 发单结束倒计时
                    $item->imgs = [];
                    $item->loaded = false;
                    $item->cancelable = $item->status === Data::DATA_DB_EXPLORE_ORDER_STATUS_PENDING && $item->total_num === $item->remaining_num;
                    return $item;
                });

            // 查询当前页订单的工单
            $eo_ids = $explore_history->pluck('eo_id')->toArray();
            $works = DB::table('explore_work as ew')
                ->leftJoin('lottery_users as lu', 'ew.receiver_we_id', '=', 'lu.we_id')
                ->leftJoin('talent', 'ew.talent_id', '=', 'talent.talent_id')
                ->whereIn('ew.eo_id', $eo_ids)
                ->select('ew.eo_id', 'ew.work_id', 'ew.work_no', 'ew.status', 'ew.error_reason', 'ew.receive_time', 'ew.receiver_we_id', 'lu.nickname', 'lu.phone', 'lu.headimgurl',
                    'ew.talent_id', 'talent.account_name as talent_name', 'talent.verify_img', 'ew.submit_time', 'ew.submit_img','ew.submit_remark','ew.accept_time','ew.accept_remark',
                    'ew.settlement_time', 'ew.settlement_user','ew.updated_at')
                ->get()
                ->mapWithKeys(function($item){
                    $item->step = Work::workSteps($item->status,$item->error_reason);
                    $item->submit_img = AliOss::getUrl($item->submit_img);
                    $item->logs = Work::workLog($item->work_id);
                    $item->status_name = Data::$exploreWorkStatus[$item->status];
                    // （拒回）投稿超时时间
                    if($item->status === Data::DATA_DB_EXPLORE_WORK_STATUS_REFUSE){
                        $item->canceled_at = Period::getSetting('EXPLORE_UPLOAD_OVERTIME') - (time() - strtotime($item->updated_at));
                    }
                    // 自动认证时间
                    if($item->status === Data::DATA_DB_EXPLORE_WORK_STATUS_SUBMIT){
                        $item->passed_at =  Period::getSetting('EXPLORE_ACCEPTANCE_OVERTIME') - (time() - strtotime($item->updated_at));
                    }

                    return [$item->eo_id => $item];
                })
                ->toArray();
            $works = json_decode(json_encode($works), true);

            // 工单合并入订单
            $result = $explore_history->toArray();
            $result = json_decode(json_encode($result), true);
            foreach($result as &$explore){
                if(isset($works[$explore['eo_id']])) {
                    $explore['works'] = [$works[$explore['eo_id']]];
                    //（接单）投稿超时时间
                    //如果工单是已接单状态，过期时间按照探店订单截止日后延固定时间
                    if($explore['works'][0]['status'] === Data::DATA_DB_EXPLORE_WORK_STATUS_INIT){
                        $end_time = strtotime($explore['end_date'].'00:00:00') + Period::getSetting('EXPLORE_UPLOAD_OVERTIME');
                        $explore['works'][0]['canceled_at'] = $end_time - time();
                    }
                } else {
                    $explore['works'] = [];
                }
            }

            return $this->setReturnJson(0,'success',$result);
        } catch (\Exception $e) {
            Log::error(HistoryExploreController::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            return $this->setReturnJson(-1, '信息查询失败');
        }
    }
}
